const { data } = require("jquery");
var $ = require("jquery");
//--------模型层--------------

//所有购物车商品信息的模型
var cartItemList;

//登陆界面的HTML
const loginHtml = `<div id="Content">
        <div id="Catalog">
            <form id="loginForm" action="#" method="post">
                <p>Please enter your username and password.</p>
                <p>
                    Username:<input type="text" name="username" value="j2ee"><br/>
                    Password:<input type="password" name="password" value="j2ee"><br/>
                </p>
                <a class="Button" id="signon" href="signon1">login</a>
            </form>
            Need a user name and password?
            <a href="viewNewAccount">Register Now!</a>
            <a href="viewSignonAdmin">Admin Login</a>
        </div>
    </div>`;

//主界面HTML
const mainHtml = `<div id="Content">
        <div id="Welcome">
            <div id="WelcomeContent">
                Welcome to MyPetStore!
            </div>
        </div>

        <div id="Main">
            <div id="Sidebar">
                <div id="SidebarContent">
                    <a href="no"></a>
                    <br/><label></label><br/>
                </div>
            </div>

            <div id="MainImage">
                <div id="MainImageContent">
                    <map name="estoremap">
                        <area alt="Birds" coords="72,2,280,250" href="viewCategory?categoryId=BIRDS" shape="rect" />
                        <area alt="Fish" coords="2,180,72,250" href="viewCategory?categoryId=FISH" shape="rect" />
                        <area alt="Dogs" coords="60,250,130,320" href="viewCategory?categoryId=DOGS" shape="rect" />
                        <area alt="Reptiles" coords="140,270,210,340" href="viewCategory?categoryId=REPTILES" shape="rect" />
                        <area alt="Cats" coords="225,240,295,310" href="viewCategory?categoryId=CATS" shape="rect" />
                        <area alt="Birds" coords="280,180,350,250" href="viewCategory?categoryId=BIRDS" shape="rect" />
                    </map>
                    <img height="355" src="../images/splash.gif" align="middle" usemap="#estoremap" width="350" />
                </div>
            </div>
            <div id="Separator">&nbsp;
                <a href="viewMessage">
                    <img src="../images/message.jpg" align="right" alt="message_box">
                </a>
            </div>
        </div>
    </div>`;

//构造购物车的界面
const getCartHtml = function(data){
    subTotalPrice = 0;
    var trData = "";
    if(data.length == 0)
        trData = `<tr><td colspan="8"><b>Your cart is empty.</b></td></tr>`;
    for(let i = 0; i < data.data.length; i++){
        temp = data.data[i];
        item = temp.item;
        itemId = item.itemId;
        trData += `<tr>
            <td><a href="${itemId}">${itemId}</a></td>
            <td>${item.productId}</td>
            <td><label>${item.attribute1}</label></td>
            <td>${temp.inStock}</td>
            <td><input type="text" name="${itemId}" value="${temp.quantity}"/></td>
            <td><input type="hidden" name="${itemId+'itemPrice'}"  value="${item.listPrice}"/>${item.listPrice}</td>
            <td name="${item.itemId+'totalPrice'}">${temp.total}</td>
            <td><a name="remove" class="Button" href="removeItemFromCart?workingItemId=${itemId}"> Remove</a>
            <input type="hidden" value="${itemId}"/></td>
        </tr>`
        subTotalPrice += temp.total;
    }

    return `<div id="Content">
        <div id="Cart">
            <h2>Shopping Cart</h2>
            <form action="updateCartQuantities" method="post">
                <table>
                    <tr class="head">
                        <th><b>Item ID</b></th>
                        <th><b>Product ID</b></th>
                        <th><b>Description</b></th>
                        <th><b>In Stock?</b></th>
                        <th><b>Quantity</b></th>
                        <th><b>List Price</b></th>
                        <th><b>Total Cost</b></th>
                        <th>&nbsp;</th>
                    </tr>
                    ${trData}
                    <tr>
                        <td name="subTotalPrice" colspan="7">
                            Sub Total: $ ${subTotalPrice}</td>
                        <td>&nbsp;</td>
                    </tr>
                </table>
            </form>
        </div>
        <div id="Separator">&nbsp;</div>
    </div>`;
}

//得到cartItemList
function getCartItemList(){
    return new Promise((resolve) => {
        $.get({
            xhrFields: {
                withCredentials: true
            },
            url: "http://192.168.217.217:8080/cartItems"
        }).done(function(data){
            resolve(data);
        })
    })
}

//提交登录表单内容
function login(){
    return new Promise((resolve)=>{
        $.post({
            data: $("#loginForm").serialize(),
            xhrFields: {
                //表示进行会话跟踪
                withCredentials: true
            },
            url: "http://192.168.217.217:8080/signon"
        }).done(function(data){
            resolve(data);
        });
    })
}

//修改商品的数量
function changeQuantity(itemId, quantityNum){
    return new Promise((resolve)=>{
        $.ajax({
            method: "PATCH",
            data: {quantity: quantityNum},
            xhrFields: {
                withCredentials: true
            },
            url: "http://192.168.217.217:8080/cartItems/"+ itemId
        }).done(function(data){
            resolve(data);
        });
    })
}

//删除商品
function deleteCartItem(itemId){
    return new Promise((resolve)=>{
        $.ajax({
            method: "DELETE",
            xhrFields: {
                withCredentials: true
            },
            url: "http://192.168.217.217:8080/cartItems/" + itemId
        }).done(function(data){
            resolve(data);
        });
    })
}

//-------控制层------------

//刷新后查看当前界面
$(async function(){
    var nowHtml = sessionStorage.getItem("nowHtml") || "mainHtml";
    if (nowHtml == "mainHtml")
        $("#Content").replaceWith(mainHtml);
    else if (nowHtml == "loginHtml")
        $("#Content").replaceWith(loginHtml);
    else if (nowHtml == "cartHtml"){
        var data = await getCartItemList();//得到cartItemList
        cartItemList = data.data;
        $("#Content").replaceWith(getCartHtml(data));
    }
})

//得到某cartItemList的具体商品
function indexOfCartItem(itemId){
    for(var i = 0; i < cartItemList.length; i++)
        if(itemId == cartItemList[i].itemId)
            return i;
}

//购物车的总值
function getSubTotalPrice(){
    var subTotalPrice = 0;
    for(let i = 0; i < cartItemList.length; i++)//所有tr标签个数减2代表个数
        subTotalPrice += cartItemList[i].total;
    return subTotalPrice;
}

//跳转到登录界面
$("#signIn").on("click", function(event){
    event.preventDefault();
    sessionStorage.setItem("nowHtml", "loginHtml");
    $("#Content").replaceWith(loginHtml);
})

//跳转到主界面
$("#main").on("click", function(event){
    event.preventDefault();
    sessionStorage.setItem("nowHtml", "mainHtml");
    $("#Content").replaceWith(mainHtml);
})

//跳转到购物车界面
$("#viewCart").on("click", async function(event){
    event.preventDefault();
    sessionStorage.setItem("nowHtml", "cartHtml");
    var data = await getCartItemList();//得到cartItemList
    cartItemList = data.data;
    $("#Content").replaceWith(getCartHtml(data));
})

//登录请求，因为是动态添加的标签所以语法不同
$("body").on("click", "#signon", async function(event){
    event.preventDefault();
    await login();
    $("#Content").replaceWith(mainHtml);
})

//修改购物车数量
$("body").on("blur", "input:text", async function(){
    var itemId = this.name;//得到触发事件的商品ID
    var quantityNum = $("input[name='"+itemId+"']").val();//得到修改后的数量
    cartItem = cartItemList[indexOfCartItem(itemId)];//获得cartItem
    cartItem.quantity = quantityNum;//改数量
    cartItem.total = quantityNum * cartItem.item.listPrice;//改总价
    if (quantityNum < 1){//不允许修改到小于1
        $(this).val(1);
        cartItem.quantity = quantityNum = 1;
        cartItem.total = cartItem.item.listPrice;
    }
    var data = await changeQuantity(itemId, quantityNum);
    $("[name='"+itemId+"totalPrice']").text("$" + cartItem.total);//修改货物总值
    if(data.status == 0)//如果成功了
        $("[name='subTotalPrice']").text("Sub Total: $" + getSubTotalPrice());//修改所有货物总值
})

//删除表项
$("body").on("click", "[name='remove']", async function (e) {
    e.preventDefault();
    var itemId = $(this).next().val();
    cartItemList.splice(indexOfCartItem(itemId), 1);//将该元素从本地删除
    await deleteCartItem(itemId);//删除服务器
    $("[name='" + itemId + "totalPrice']").parent().remove();//删除
    $("[name='subTotalPrice']").text("Sub Total: $"+ getSubTotalPrice());//修改所有货物总值
    if (cartItemList == null)//如果为空则提示
        $(".head").after("<tr class=\"even\"><td colspan=\"8\"><b>Your cart is empty.</b></td></tr>");
})